package com.yl.zqy.controller.sys;

import com.yl.zqy.common.CustomException;
import com.yl.zqy.common.Result;
import com.yl.zqy.dto.SysMenuDTO;
import com.yl.zqy.entity.sys.SysMenu;
import com.yl.zqy.enums.ResultCode;
import com.yl.zqy.service.sys.SysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 * @author liang.yu
 * @since 2024-03-25
 */
@RestController
@RequestMapping("/sysMenu")
@Tag(name = "菜单管理", description = "SysMenuController")
@RequiredArgsConstructor
public class SysMenuController {
    private final SysMenuService menuService;

    @PostMapping("/add")
    @Operation(summary = "新增菜单", tags = "菜单管理")
    public Result<Boolean> insertMenu(@RequestBody SysMenu menu) {
        return menuService.insertMenu(menu);
    }

    @PutMapping("/update")
    @Operation(summary = "修改菜单", tags = "菜单管理")
    public Result<Boolean> updateMenu(@RequestBody SysMenu menu) {
        Optional.ofNullable(menu.getId()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "ID不能为空！"));
        return menuService.updateMenu(menu);
    }

    @DeleteMapping("/deleteById/{id}")
    @Operation(summary = "删除菜单（根据ID）", tags = "菜单管理")
    public Result<Boolean> deleteById(@Parameter(description = "id") @PathVariable(value = "id") String id) {
        Optional.ofNullable(id).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "ID不能为空！"));
        //判断是否有子菜单或按钮
        List<SysMenuDTO> list = menuService.getListPid(id);
        if (list.size() > 0) {
            throw new CustomException(ResultCode.PARAMS_ERROR, "当前菜单下有子菜单或按钮，不能删除！");
        }
        return Result.ok(menuService.removeById(id));
    }

    @GetMapping("/menuList")
    @Operation(summary = "菜单列表", tags = "菜单管理")
    public Result<List<SysMenuDTO>> menuAllList(
            @Parameter(description = "状态") @RequestParam(value = "status", required = false) String status,
            @Parameter(description = "菜单名称") @RequestParam(value = "name", required = false) String name) {
        return Result.ok(menuService.menuAllList(status, name));
    }
    @GetMapping("/menuSelectTree")
    @Operation(summary = "菜单下拉树", tags = "菜单管理")
    public Result<List<SysMenuDTO>> menuSelectTree() {
        return Result.ok(menuService.menuSelectTree());
    }


}
